package com.feng.cloud.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.cloud.common.constants.SystemConstant;
import com.feng.cloud.common.exception.SystemException;
import com.feng.cloud.common.exception.system.ParameterException;
import com.feng.cloud.common.exception.system.SystemStatus;
import com.feng.cloud.common.request.QueryRequest;
import com.feng.cloud.common.utils.SortUtils;
import com.feng.cloud.system.entity.Role;
import com.feng.cloud.system.entity.RoleMenu;
import com.feng.cloud.system.entity.SystemUser;
import com.feng.cloud.system.mapper.RoleMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName RoleService
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/26 11:24
 * @Version 1.0
 **/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@AllArgsConstructor
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    private final RoleMapper roleMapper;
    private final RoleMenuService roleMenuService;
    private final UserRoleService userRoleService;

    public List<Role> selectList() {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Role::getRoleId);
        return roleMapper.selectList(queryWrapper);
    }

    public IPage<Role> selectListByPage(QueryRequest request) {
        // 分页
        Page<SystemUser> page = new Page<>();
        SortUtils.handlePageAndSort(request,page,Role::getCreateTime, SystemConstant.ORDER_DESC,false);
        return roleMapper.selectListByPage(page, request);
    }

    public Role selectRoleByName(String roleName) {
        if (StringUtils.isBlank(roleName)) {
            throw new ParameterException(SystemStatus.ROLE_NAME_EMPTY);
        }
        // 替换空格
        roleName = roleName.replaceAll(StringPool.SPACE, StringPool.EMPTY);
        return roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, roleName));
    }

    /**
     * 保存角色和菜单信息
     * @param role Role
     */
    public void addRoleAndMenus(Role role) {
        role.setCreateTime(LocalDateTime.now());
        this.save(role);
        // 保存菜单信息
        if (StringUtils.isNotBlank(role.getMenuIds())) {
            String[] menuIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(role.getMenuIds(), ",");
            setRoleMenus(role, menuIds);
        }
    }

    private void setRoleMenus(Role role, String[] menuIds) {
        List<RoleMenu> roleMenus = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            if (StringUtils.isNotBlank(menuId)) {
                roleMenu.setMenuId(Long.valueOf(menuId));
            }
            roleMenu.setRoleId(role.getRoleId());
            roleMenus.add(roleMenu);
        });
        this.roleMenuService.saveBatch(roleMenus);
    }

    public void updateRoleById(Role role) {
        Long roleId = role.getRoleId();
        if (roleId == null) {
            throw new SystemException(SystemStatus.ROLE_ID_EMPTY);
        }
        role.setModifyTime(LocalDateTime.now());
        roleMapper.updateById(role);
        // 删除角色对应的菜单
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
        // 保存菜单信息
        if (StringUtils.isNotBlank(role.getMenuIds())) {
            String[] menuIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(role.getMenuIds(), ",");
            setRoleMenus(role, menuIds);
        }
    }

    public void deleteRoles(String[] idArr) {
        List<String> idList = Arrays.asList(idArr);
        this.baseMapper.deleteBatchIds(idList);
        // 删除角色对应的菜单
        roleMenuService.deleteRoleMenusByRoleIds(idList);
        // 删除用户关联的角色
        userRoleService.deleteUserRolesByRoleId(idList);
    }
}
